<template>
  <div class="table-page">
    <a-form
      label-align="right"
      layout="inline"
      auto-label-width
      :model="listParams"
      size="small"
      class="form mt-10 mb-20"
    >
      <a-form-item hide-label field="sourceChatroomId">
        <a-select class="w-70n" v-model="listParams.sourceChatroomId" placeholder="全部源头群" @change="getTableData">
          <a-option :value="item.sourceChatRoomId" v-for="item in sourceList" :key="item.sourceChatRoomId">{{
            item.name
          }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item hide-label field="platformId">
        <a-select v-model="listParams.platformId" class="w-50n" placeholder="选择平台" @change="getTableData">
          <a-option value="" label="全部平台"></a-option>
          <a-option
            v-for="item in platformList"
            :key="item.sourceType"
            :value="item.sourceType"
            :label="item.title"
          ></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="status" hide-label>
        <a-select v-model="listParams.status" class="w-50n" placeholder="选择用户状态" @change="getTableData">
          <a-option value="" label="全部"></a-option>
          <a-option :value="1" label="在线"></a-option>
          <a-option :value="0" label="离线"></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="startAt" hide-label>
        <ms-date
          v-model:start="listParams.startAt"
          :disabledDate="
            (current) =>
              dayjs(current).isAfter(dayjs().endOf('date')) ||
              dayjs(current).isBefore(dayjs('2023-09-07').startOf('date'))
          "
          v-model:end="listParams.endAt"
          :showQuick="true"
          @dateChange="getTableData"
        ></ms-date>
      </a-form-item>
      <a-form-item field="inviteCode" hide-label>
        <a-input
          class="w-40n"
          v-model="listParams.inviteCode"
          placeholder="输入用户邀请码筛选"
          @press-enter="getTableData"
        ></a-input>
      </a-form-item>
      <a-form-item>
        <a-space class="flex-center">
          <a-button type="primary" size="small" @click="getTableData">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <div class="flex flex-wrap w-full pl-10 box-border">
      <ms-data-card title="总GMV（元）" :value="totalData?.totalGmv ?? 0" :precision="2"></ms-data-card>
      <ms-data-card title="有效GMV（元）" :value="totalData?.validGmv ?? 0" :style="2" :precision="2"></ms-data-card>
      <ms-data-card
        title="总订单量（单）"
        :value="totalData?.totalOrderCount ?? 0"
        :style="3"
        :precision="0"
      ></ms-data-card>
      <ms-data-card
        title="有效订单（单）"
        :value="totalData?.validOrderCount ?? 0"
        :style="4"
        :precision="0"
      ></ms-data-card>
      <ms-data-card
        title="预估佣金（元）"
        :value="totalData?.totalCommission ?? 0"
        :style="6"
        :precision="2"
      ></ms-data-card>
    </div>
    <GiTable
      row-key="userWechatId"
      ref="tt"
      id="groupUserOrder"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
      @sorter-change="onSorterChange"
    >
      <template #info="{ record }">
        <div class="flex flex-a-c">
          <ImgHoverPreview :url="record?.wxInfo?.vcHeadImgUrl" round="50%" />
          <div class="ml-8">
            <div>{{ record?.wxInfo?.vcNickName || '--' }}</div>
            <div class="text-size-12">{{ record?.wxInfo?.vcRobotWxId || '--' }}</div>
          </div>
        </div>
      </template>
      <template #platform="{ record }">
        <template v-if="record.name">
          <span>{{ record.name }}</span>
        </template>
        <template v-else>
          <a-button type="text" size="small" @click="onMore(record.userWechatId, !record.isOpen)">
            {{ record.isOpen ? '收起' : '展开查看' }}
          </a-button>
        </template>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { useSource, usePlatform } from '@/hooks/app'
import { sourceChatRoomUserOrderData, wechatListByIds } from '@/apis'
import { deleteEmpty } from '@/utils/common'
import { statusArr } from '../../equipment/data'
import GiDot from '@/components/GiDot/index.vue'

defineOptions({ name: 'groupUserOrder' })
const tableDataO = ref([])
const tableDataC = ref([])
const tableData = ref([])
const loading = ref(false)
const tt = ref()
const route = useRoute()
const totalData = ref({
  totalGmv: 0,
  validGmv: 0,
  totalOrderCount: 0,
  validOrderCount: 0,
  totalCommission: 0
})

// 公共参数
const listParams = reactive({
  startAt: route.query.startAt,
  endAt: route.query.endAt,
  status: undefined,
  inviteCode: undefined,
  platformId: route.query.platformId,
  sourceChatroomId: Number(route.query.sourceChatroomId)
})

const pagination = reactive({
  showTotal: true,
  current: 1,
  showJumper: true,
  pageSize: 20,
  total: 0,
  onChange: (size) => {
    pagination.current = size
    getDataWidthPage(size)
  }
})

const columns = ref([
  {
    title: '用户信息',
    width: 180,
    slotName: 'info'
  },
  {
    title: '用户邀请码',
    width: 110,
    align: 'center',
    render(data) {
      const text = data.record.inviteCode
      return text || '--'
    }
  },
  {
    title: '设备状态',
    width: 120,
    dataIndex: 'status',
    align: 'center',
    render: (data) => {
      const status = data.record.status
      const type = statusArr[status] ? statusArr[status].type : 'info'
      const text = statusArr[status] ? statusArr[status].desc : '未知'
      return h(GiDot, {
        animation: false,
        type: type,
        text: `${text}`
      })
    }
  },
  {
    title: '统计区间',
    width: 180,
    align: 'center',
    render: ({ record }) => {
      return record.date || '--'
    }
  },
  {
    title: '跟发数据',
    width: 150,
    align: 'center',
    dataIndex: 'followStatus',
    render: ({ record }) => {
      return record.followGroupMoment
    }
  },
  {
    title: '各平台数据',
    width: 180,
    align: 'center',
    slotName: 'platform'
  },
  {
    title: '总订单量',
    width: 120,
    align: 'center',
    dataIndex: 'totalOrderCount',
    render: ({ record }) => {
      return record.totalOrderCount === 0 ? 0 : record.totalOrderCount || '--'
    },
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效订单',
    width: 120,
    align: 'center',
    dataIndex: 'validOrderCount',
    render: ({ record }) => {
      return record.validOrderCount === 0 ? 0 : record.validOrderCount || '--'
    },
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '总GMV',
    width: 120,
    align: 'center',
    dataIndex: 'totalGmv',
    render: ({ record }) => {
      return record.totalGmv === 0 ? 0 : record.totalGmv || '--'
    },
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效GMV',
    width: 120,
    align: 'center',
    dataIndex: 'validGmv',
    render: ({ record }) => {
      return record.validGmv === 0 ? 0 : record.validGmv || '--'
    },
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '总佣金',
    width: 120,
    align: 'center',
    dataIndex: 'totalCommission',
    render: ({ record }) => {
      return record.totalCommission === 0 ? 0 : record.totalCommission || '--'
    },
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  }
])

// 获取源头群
const { sourceList, getSourceList } = useSource()
getSourceList()

// 获取平台
const { platformList, getPlatformList } = usePlatform()
getPlatformList()

// 获取某一页的数据
const getDataWidthPage = (page) => {
  const table = tableDataO.value.slice((page - 1) * pagination.pageSize, pagination.pageSize * page)
  pagination.current = page
  const ids = []
  const tableconstFormat = table.map((item) => {
    ids.push(item.userWechatId)
    return {
      ...item,
      date: `${listParams.startAt || '--'}\n${listParams.endAt || '--'}`,
      children: item.platforms || [],
      isOpen: false
    }
  })
  wechatListByIds({ ids }).then((res) => {
    tableData.value = tableconstFormat.map((item, index) => {
      return {
        ...item,
        followGroupMoment: res.data.list[index].followGroupMoment
      }
    })
  })
}

// 获取头部信息
const getTableData = async () => {
  try {
    loading.value = true
    const res = await sourceChatRoomUserOrderData(deleteEmpty(listParams))
    totalData.value = res.data.totalData
    tableDataO.value = res.data.userOrderData
    tableDataC.value = JSON.parse(JSON.stringify(tableDataO.value))
    getDataWidthPage(1)
    pagination.total = res.data.userOrderData.length ?? 0
  } finally {
    loading.value = false
  }
}
getTableData()

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  const orderBy = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  const sort = orderBy ? dataIndex : undefined
  if (!orderBy) {
    tableDataO.value = JSON.parse(JSON.stringify(tableDataC.value))
  } else {
    tableDataO.value.sort(function (a, b) {
      if (a[sort] < b[sort]) {
        return orderBy === 'asc' ? -1 : 1
      }
      if (a[sort] > b[sort]) {
        return orderBy === 'asc' ? 1 : -1
      }
      return 0
    })
  }
  getDataWidthPage(1)
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.startAt = listParams.endAt = listParams.status = listParams.inviteCode = listParams.platformId = undefined
  getTableData()
}

//点击展开更多
const onMore = (id, type) => {
  if (type) {
    tableData.value.forEach((item) => {
      item.isOpen = false
    })
    tt.value.tableRef.expandAll(false)
  }
  tt.value.tableRef.expand(id, type)
  const index = tableData.value.findIndex((item) => {
    return item.userWechatId === id
  })
  tableData.value[index].isOpen = type
}
</script>

<style lang="scss" scoped>
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .form {
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  :deep(.arco-table-cell-inline-icon) {
    display: none;
  }
}
</style>
